<template>
    <div class="station-container">
        <div class="header">
            <h1>再生道回收站工作台</h1>
            <p class="slogan">专业环保服务，从这里开始</p>
        </div>
        
        <div class="orders-box">
            <div class="station-section">
                <h3><i class="el-icon-office-building"></i> 工作站信息</h3>
                <div class="station-info">
                    <el-button 
                        type="primary"
                        size="small"
                        icon="el-icon-refresh"
                        @click="fetchOrders"
                        :loading="loading"
                    >刷新订单</el-button>
                </div>
            </div>

            <!-- 订单状态选项卡 -->
            <el-tabs v-model="activeTab" @tab-click="handleTabClick">
                <el-tab-pane label="全部订单" name="all"></el-tab-pane>
                <el-tab-pane label="待接单" name="1"></el-tab-pane>
                <el-tab-pane label="已接单" name="2"></el-tab-pane>
                <el-tab-pane label="已完成" name="3"></el-tab-pane>
                <el-tab-pane label="已取消" name="5"></el-tab-pane>
            </el-tabs>

            <div class="orders-section">
                <h3>
                    <i class="el-icon-s-order"></i> 
                    {{ getStatusTitle(activeTab) }}
                    <span class="order-count">(共 {{ total }} 个订单)</span>
                </h3>
                
                <div class="order-list" v-loading="loading">
                    <template v-if="filteredOrders.length > 0">
                        <el-card v-for="order in filteredOrders" 
                                :key="order.recyclingOrderNum" 
                                class="order-card"
                                :shadow="'hover'"
                        >
                            <div class="order-header">
                                <span class="order-num">订单号：{{ order.recyclingOrderNum }}</span>
                                <el-tag :type="getStatusType(order.status)">{{ getStatusText(order.status) }}</el-tag>
                            </div>
                            
                            <div class="order-content">
                                <div class="order-info">
                                    <p>
                                        <i class="el-icon-date"></i> 
                                        创建时间：{{ formatTime(order.createdAt) }}
                                    </p>
                                    <p v-if="order.appointmentTime">
                                        <i class="el-icon-time"></i> 
                                        预约时间：{{ formatTime(order.appointmentTime) }}
                                    </p>
                                    <p v-if="order.appointPhone">
                                        <i class="el-icon-mobile-phone"></i> 
                                        联系电话：{{ order.appointPhone }}
                                    </p>
                                    <p>
                                        <i class="el-icon-location"></i> 
                                        回收地址：{{ formatAddress(order) }}
                                    </p>
                                    <p v-if="order.remarks">
                                        <i class="el-icon-document"></i> 
                                        备注信息：{{ order.remarks }}
                                    </p>
                                </div>
                                
                                <div class="order-actions">
                                    <el-button 
                                        v-if="order.status === 1"
                                        type="success" 
                                        size="small"
                                        @click="acceptOrder(order.recyclingOrderNum)"
                                        :loading="acceptLoading === order.recyclingOrderNum"
                                    >接单</el-button>
                                    <el-button 
                                        v-if="order.status === 2"
                                        type="primary" 
                                        size="small"
                                        @click="completeOrder(order.recyclingOrderNum)"
                                        :loading="completeLoading === order.recyclingOrderNum"
                                    >完成订单</el-button>

                                    <el-button 
                                        type="info" 
                                        size="small"
                                        icon="el-icon-view"
                                        @click="viewOrderDetail(order.recyclingOrderNum)"
                                    >查看详情</el-button>
                                </div>
                            </div>
                        </el-card>
                    </template>
                    
                    <div v-else class="empty-orders">
                        <i class="el-icon-tickets"></i>
                        <p>暂无{{ getStatusText(activeTab) }}订单</p>
                    </div>
                    
                    <!-- 分页控件 -->
                    <el-pagination
                        v-if="total > 0"
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page="pageNum"
                        :page-sizes="[5, 10, 20, 50]"
                        :page-size="pageSize"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="total">
                    </el-pagination>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
export default {
    name: 'StationOrders',
    data() {
        return {
            orders: [],
            loading: false,
            acceptLoading: null,
            chatLoading: null,
            completeLoading: null,
            refreshTimer: null,
            activeTab: 'all',
            pageNum: 1,
            pageSize: 10,
            total: 0,
            stationId: null // 临时使用，实际应从登录信息获取
        }
    },
    computed: {
        filteredOrders() {
            if (this.activeTab === 'all') {
                return this.orders;
            } else {
                return this.orders.filter(order => order.status.toString() === this.activeTab);
            }
        }
    },
    
    mounted() {
        this.getSiteId()
        
        // 每30秒自动刷新一次订单
        this.refreshTimer = setInterval(this.fetchOrders, 30000)
    },
    beforeDestroy() {
        if (this.refreshTimer) {
            clearInterval(this.refreshTimer)
        }
    },
    methods: {
        async getSiteId() {
      try {
        const resp = await this.$http.get('/platform/recycleBin/selectStationIdByAccountId')
        if (resp.data.code === 200) {
              this.stationId = resp.data.data;
              console.log(this.siteId);
              this.fetchOrders()
        }
        } catch (error) {
            console.log(error);
          this.$message.error('获取站点ID失败')
      }
      },
        // 获取订单列表
        async fetchOrders() {
            // if (!this.stationId) {
            //     this.$message.warning('请先登录')
            //     this.$router.push('/login')
            //     return
            // }
            
            this.loading = true
            console.log("读取订单时是否获取到"+this.stationId)
            try {
                const response = await this.$http.post('/recycle/recyclingOrder/stationSelectOrderByCondition', {
                    pageNum: this.pageNum,
                    pageSize: this.pageSize,
                    stationId: this.stationId
                })
                
                if (response.data.code === 200) {
                    this.orders = response.data.data.list
                    this.total = response.data.data.total
                    this.pageNum = response.data.data.pageNum
                } else {
                    this.$message.error(response.data.message || '获取订单失败')
                }
            } catch (error) {
                console.error('获取订单错误:', error)
                this.$message.error('获取订单失败')
            } finally {
                this.loading = false
            }
        },
        
        // 接受订单
        async acceptOrder(orderNum) {
            this.acceptLoading = orderNum
            try {
                const response = await this.$http.post('/recycle/recyclingOrder/receivingOrders', {
                    recyclingOrderNum: orderNum,
                    stationId: this.stationId
                })
                
                if (response.data.code === 200) {
                    this.$message.success('接单成功')
                    this.fetchOrders() // 刷新订单列表
                } else {
                    this.$message.error(response.data.message || '接单失败')
                }
            } catch (error) {
                console.error('接单错误:', error)
                this.$message.error('接单失败，请重试')
            } finally {
                this.acceptLoading = null
            }
        },
        
        // 完成订单
        async completeOrder(orderNum) {
            this.completeLoading = orderNum
            try {
                const response = await this.$http.post('/recycle/recyclingOrder/completeOrder', {
                    recyclingOrderNum: orderNum
                })
                
                if (response.data.code === 200) {
                    this.$message.success('订单已完成')
                    this.fetchOrders() // 刷新订单列表
                } else {
                    this.$message.error(response.data.message || '操作失败')
                }
            } catch (error) {
                console.error('完成订单错误:', error)
                this.$message.error('操作失败，请重试')
            } finally {
                this.completeLoading = null
            }
        },
        

        
        // 查看订单详情
        viewOrderDetail(orderNum) {
            this.$router.push({
                path: '/platform/order-detail',
                query: { orderNum }
            })
        },
        
        // 格式化时间
        formatTime(time) {
            if (!time) return '未设置'
            return new Date(time).toLocaleString()
        },
        
        // 格式化地址
        formatAddress(order) {
            return [order.city, order.district, order.street]
                .filter(Boolean)
                .join(' ')
        },
        
        // 获取订单状态文本
        getStatusText(status) {
            const statusMap = {
                '1': '待接单',
                '2': '已接单',
                '3': '已完成',
                '4':'待评价',
                '5': '已取消',
                '6':'取件中',
                'all': '全部'
            }
            return statusMap[status] || '未知状态'
        },
        
        // 获取订单状态标签类型
        getStatusType(status) {
            const typeMap = {
                '1': 'warning',
                '2': 'primary',
                '3': 'success',
                '4':'warning',
                '5': 'info',
                '6':'warning'
            }
            return typeMap[status] || 'info'
        },
        
        // 获取标题
        getStatusTitle(status) {
            if (status === 'all') return '全部订单';
            return this.getStatusText(status) + '订单';
        },
        
        // 处理标签页切换
        handleTabClick() {
            this.pageNum = 1;
            this.fetchOrders();
        },
        
        // 处理每页显示数量变化
        handleSizeChange(val) {
            this.pageSize = val;
            this.fetchOrders();
        },
        
        // 处理页码变化
        handleCurrentChange(val) {
            this.pageNum = val;
            this.fetchOrders();
        }
    }
}
</script>

<style scoped>
.station-container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
    min-height: 100vh;
    background-color: #f0f9eb;
}

.header {
    text-align: center;
    margin-bottom: 30px;
    padding: 20px 0;
}

.header h1 {
    color: #67c23a;
    font-size: 2.5em;
    margin-bottom: 10px;
}

.slogan {
    color: #606266;
    font-size: 1.2em;
    font-style: italic;
}

.orders-box {
    background: white;
    border-radius: 15px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
    padding: 30px;
}

.station-section {
    margin-bottom: 20px;
    padding-bottom: 20px;
    border-bottom: 2px solid #f0f9eb;
}

.station-info {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 16px;
    color: #303133;
}

.order-card {
    margin-bottom: 20px;
}

.order-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    padding-bottom: 10px;
    border-bottom: 1px solid #ebeef5;
}

.order-num {
    font-weight: bold;
    color: #303133;
}

.order-content {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
}

.order-info {
    flex: 1;
}

.order-info p {
    margin: 8px 0;
    color: #606266;
}

.order-info i {
    margin-right: 8px;
    color: #67c23a;
}

.order-actions {
    display: flex;
    flex-direction: column;
    gap: 10px;
    min-width: 120px;
}

.empty-orders {
    text-align: center;
    padding: 40px 0;
    color: #909399;
}

.empty-orders i {
    font-size: 48px;
    margin-bottom: 10px;
}

h3 {
    color: #67c23a;
    margin-bottom: 15px;
    display: flex;
    align-items: center;
    gap: 8px;
}

h3 i {
    font-size: 1.2em;
}

.order-count {
    font-size: 0.8em;
    color: #909399;
    margin-left: 8px;
}

.el-pagination {
    text-align: center;
    margin-top: 30px;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .station-container {
        padding: 10px;
    }

    .header h1 {
        font-size: 2em;
    }

    .orders-box {
        padding: 15px;
    }

    .order-content {
        flex-direction: column;
    }

    .order-actions {
        margin-top: 15px;
        width: 100%;
        flex-direction: row;
        flex-wrap: wrap;
        justify-content: flex-end;
    }
}
</style> 